<?
include_class('db');

class UserList {
	
	var $total = 0;
	
	function getTotal() {return $this->total;}
	
	function getAdminUsers() {
		$query = 'select Users.ID from Users left join Band_Members on (Users.ID = Band_Members.user_id) where level = "ADMIN" and Band_Members.user_id is null order by lastname asc';
		$r = mysql_query($query);		
		if ($r) { 
			$users = array();
			while ($row = mysql_fetch_assoc($r)) {
				$users[] = User::get($row['ID']);
			}
			return $users;
		} else {
			$e = new Error();
			$e->add(mysql_error());
			return $e;		
		}
	}
	
	function getActiveAdminUsers() {
		$query = 'select Users.ID from Users left join Band_Members on (Users.ID = Band_Members.user_id) where level = "ADMIN"  and Band_Members.user_id is null and Users.is_active = 1 order by lastname asc';
		$r = mysql_query($query);		
		if ($r) { 
			$users = array();
			while ($row = mysql_fetch_assoc($r)) {
				$users[] = User::get($row['ID']);
			}
			return $users;
		} else {
			$e = new Error();
			$e->add(mysql_error());
			return $e;		
		}
	}
	
	function get() {
		$args_list = func_get_args();
		$number_to_get = (int) $args_list[0];
		$start_number = (int) $args_list[1];
		
		if ($number_to_get && $start_number) {
			$query = "select ID from Users order by ID asc limit $start_number, $number_to_get";
		} else if ($number_to_get) {
			$query = "select ID from Users order by ID asc limit 0, $number_to_get";
		} else if ($start_number) {
			$query = "select ID from Users order by ID asc limit $start_number, 10";
		} else {
			$query = "select ID from Users order by ID asc limit 0, 10";
		}
		
		$q = "select count(ID) as total from Users";
		$r = mysql_query($q);
		if (!$r) {
			return Error::MySQL();
		}
		$row = mysql_fetch_assoc($r);
		$this->total = $row['total'];
		
		$r = mysql_query($query);
		if (!$r) {
			return Error::MySQL();
		}
		$user = array();
		while ($row = mysql_fetch_assoc($r)) {
			$user[] = User::get($row['ID']);
		}
		return $user;
	}
}

class User {

	var $ID, $username, $password, $firstname, $lastname, $birthdate, $is_active, $email, $level;
	
	function getID() {return $this->ID;}
	function getUserName() {return $this->username;}
	function getPassword() {return $this->password;}
	function getFirstName() {return $this->firstname;}
	function getLastName() {return $this->lastname;}
	function getBirthDate($dateMask = null) {
		$dateMask = (!$dateMask) ? DATE_FORMAT : $dateMask;
		return date($dateMask, strtotime($this->birthdate));
	}
	function isActive() {return $this->is_active;}
	function getEmailAddress() {return $this->email;}
	function getLevel() {return $this->level;}
	
	function isBandMember() {
		$q = "select ID from Band_Members where user_id = {$this->ID}";
		$r = mysql_query($q);
		if (!$r) {
			return false;
		}
		$row = mysql_fetch_assoc($r);
		if ($row['ID']) {
			return true;
		} else {
			return false;
		}
	}
	
	function add($postArray) {
		$db = new db;
		$e = new Error();
		if (User::isAdmin()) {			
			$password = $db->sanitize_to_db($postArray['password']);
			$confirmPassword = $db->sanitize_to_db($postArray['password_confirm']);
			$passwordHash = null;
			
			$username = $db->sanitize_to_db($postArray['username']);
			if ($username != null && $username != "") {
				if (User::exists($username)) {
					$e->add("A user with the username '{$username}' already exists.");
				}
			} else {
				$e->add("A user entry must contain a username.");
			}
			
			if ($password != null && $password != "") {
				// something has been entered for password
				if ($password == $confirmPassword) {
					if (strlen($password) > 4) {	
						$passwordHash = md5($password);
					} else {
						$e->add("A user password must be at least 5 characters.");
					}
				} else {
					$e->add("The two passwords do not match.");
				}
			} else {
				$e->add("A user entry must contain a password.");
			}
			
			$firstname = $db->sanitize_to_db($postArray['firstname']);
			if (!$firstname) {
				$e->add("A user entry must contain a first name.");
			}
			
			$lastname = $db->sanitize_to_db($postArray['lastname']);
			
			$_dt = strtotime($db->sanitize_to_db($postArray['birthdate']));
			$birthdate = date('Y-m-d', $_dt);
			$email = $db->sanitize_to_db($postArray['email']);
			$validAccess = array("USER", "ADMIN");
			$level = (!in_array($postArray['level'], $validAccess)) ? "USER" : $postArray['level'];
			
			if ($e->hasErrors()) {
				return $e;
			} else {
				$result = @mysql_query("insert into Users (username, password, lastname, firstname, email, birthdate, level) values ('$username', '$passwordHash', '$lastname', '$firstname', '$email', '$birthdate', '$level')");
				if (!$result) {
					$e->add(mysql_error());
				} else {
					$userID = mysql_insert_id();
				}
				
				if ($e->hasErrors()) {
					return $e;
				} else {
					$uo = User::get($userID);
					return $uo;
				}
			}			
			
		} else {
			$e->add('You may not add users. Only an admin user may do that.');
			return $e;
		}
	}
	
	function update($postArray) {
		$db = new db;
		$e = new Error();
		if (User::isAdmin()) {	
			$password = $db->sanitize_to_db($postArray['password']);
			$confirmPassword = $db->sanitize_to_db($postArray['password_confirm']);
			$passwordHash = null;
			if ($password != null && $password != "") {
				// something has been entered for password
				if ($password == $confirmPassword) {
					if (strlen($password) > 4) {	
						$passwordHash = md5($password);
					} else {
						$e->add("A user password must be at least 5 characters.");
					}
				} else {
					$e->add("The two passwords do not match.");
				}
			}
						
			$firstname = $db->sanitize_to_db($postArray['firstname']);
			if (!$firstname) {
				$e->add("A user entry must contain a first name.");
			}
			
			$lastname = $db->sanitize_to_db($postArray['lastname']);
			$email = $db->sanitize_to_db($postArray['email']);			
			$_dt = strtotime($db->sanitize_to_db($postArray['birthdate']));
			$birthdate = date('Y-m-d', $_dt);			
			$validAccess = array("USER", "ADMIN");
			$level = (!in_array($postArray['level'], $validAccess)) ? "USER" : $postArray['level'];
			
			if ($e->hasErrors()) {
				return $e;
			} else {
				// first we update the users record
				$passwordQuery = ($passwordHash != null) ? "password = '{$passwordHash}'," : "";
				
				$result = @mysql_query("update Users set {$passwordQuery} lastname='$lastname', firstname='$firstname', birthdate='$birthdate', email='$email', level = '$level' where ID = {$this->ID}");
				if (!$result) {
					$e->add(mysql_error());
				}
				
				if ($e->hasErrors()) {
					return $e;
				} else {
					return true;
				}
			}
		} else {
			$e->add("You may not edit this user's information.");
			return $e;
		}
	}
	
	function deactivate() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("update Users set is_active = 0 where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not deactivate this user.');
			return $e;
		}
	}
	
	function activate() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("update Users set is_active = 1 where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not activate this user.');
			return $e;			
		}
	}
	
	function remove() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("delete from Users where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not remove this user.');
			return $e;			
		}
	}
	
	function get($userID) {
		if ($userID > 0 && is_numeric($userID)) {
			$q = "select ID, firstname, lastname, birthdate, is_active, username, password, email, level from Users where ID = {$userID}";
			$r = mysql_query($q);
			$row = mysql_fetch_assoc($r);
			if ($row['ID']) {
				$uo = new User;
				$uo->ID = $row['ID'];
				$uo->username = $row['username'];
				$uo->lastname = db::sanitize_from_db($row['lastname']);
				$uo->password = $row['password'];
				$uo->firstname = db::sanitize_from_db($row['firstname']);
				$uo->birthdate = $row['birthdate'];
				$uo->is_active = $row['is_active'];
				$uo->email = $row['email'];
				$uo->level = $row['level'];
				return $uo;
			}
		}
		
		return Error::create("Invalid user ID.");
	}
			
	// static functions stored here for sanity
	function getCurrent() {
		// returns the user object stored in session for whomever is visiting the site
		if ($_SESSION['_uo']) {
			return $_SESSION['_uo'];
		}
	}
	
	function exists($username) {
		if ($username) {
			$q = "select ID from Users where username = '{$username}'";
			$r = mysql_query($q);
			return (mysql_num_rows($r) > 0);
		}
	}
	
	function protect() {
		$uo = User::getCurrent();
		if (!is_object($uo)) {
			$url = urlencode($_SERVER['REQUEST_URI']);
			header('Location: ' . SITE_WEB_DIRECTORY . LOGIN_PAGE . '?url=' . $url);
			exit;
		}
	}
	
	function logout() {
		session_unset();
		session_destroy();
	}
	
	function isAdmin() {
		$uo = User::getCurrent();
		return ($uo->getLevel() == 'ADMIN');
	}
	
	
	function login($username, $password) {
		$db = new db;
		$username = $db->sanitize_to_db($username);
		$password = md5($db->sanitize_to_db($password));	
		$q = "select ID from Users where username = '{$username}' and password = '{$password}'";
		$r = mysql_query($q);
		
		$row = mysql_fetch_assoc($r);
		if ($row['ID']) {
			$uo = User::get($row['ID']);
			$_SESSION['_uo'] = $uo;
			return true;
		} else {
			return false;
		}
	}
}
	

?>